package com.lance.answer.question_export;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.Item;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.Duration;
import java.util.*;

/**
 * 2021-10-11 获取一体化所有的课程
 */
public class GetAllAnswersByTeacherPost {


    public static List<WebElement> findElementsByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<List<WebElement>>)
                d -> d.findElements(By.cssSelector(cssSelector))));
    }

    public static WebElement findElementByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<WebElement>)
                d -> d.findElement(By.cssSelector(cssSelector))));
    }

    public static void main(String[] args) throws Exception {

        //   WebDriver driver = Util.getDriver("d:\\ynouAutoStudy\\chromedriver.exe");
        WebDriver driver = Util.getDriver(null);
        String url = "https://xjskk.open.com.cn/teacherspace-auth/#/login";
        // 打开指定的网站
        driver.get(url);
        Thread.sleep(200);

        for (WebElement we : driver.findElements(By.className("el-input__inner"))) {
            if ("text".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"lijunj"});
            }
            if ("password".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"lijunj"});
            }
        }
        driver.findElement(By.cssSelector("button[class='el-button login-ruleForm-btn el-button--primary']")).click();

        // 进入课程观察员角色的页面

        findElementByCssSelector(driver, "div[title='课程观察员']", 20).click();

        Thread.sleep(15000);


        List<Question> questions = Lists.newArrayList();
        questions.clear();
        int pageIndex = 1;
        boolean hashNextPage = true;

        InputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\1.txt");
        List<String> courseList = IOUtils.readLines(inputStream, "utf-8");


        for (String courseName : courseList) {


            while (hashNextPage) {
                try {

                    String postUrl = "https://xjskk.open.com.cn/api/teacher/teacher-space-service/testQuestions";
                    System.err.println("postUrl:" + postUrl);

                    Set<Cookie> cookies = driver.manage().getCookies();
                    String studentSpaceProfile = Util.getStudentSpaceProfile(cookies);
                    String authorization = Util.getAuthorization(cookies);
                    String cookie = Util.getCookie(cookies);
                    // 初始化头部
                    System.out.println("authorization:" + authorization);
                    System.out.println("studentSpaceProfile:" + studentSpaceProfile);
                    Map<String, String> heads = XinJiangUtil.initHttpHeads(studentSpaceProfile, authorization);

                    Map<String, Object> data = Maps.newHashMap();
                    //  jsonObject.put("openCourseId",openCourseId);
                    data.put("openCourseId", Long.parseLong(courseName));
                    data.put("pageNumber", pageIndex);
                    data.put("pageSize", 20);
                    String result = HttpUtil.post(postUrl, data, cookie, heads);
                    System.err.println("result:::" + result);
                    YiTiHuaSimpileAnswerInfo yiTiHuaSimpileAnswerInfo = JSONObject.parseObject(result, YiTiHuaSimpileAnswerInfo.class);

                    // 题目的总数；
                    int total = yiTiHuaSimpileAnswerInfo.getContent().getTotal();
                    // 总页数
                    int page = yiTiHuaSimpileAnswerInfo.getContent().getPage();

                    /**
                     * {"itemBankId":"4a2efab4-d381-4b16-a8eb-0d822a1248a6","idList":["1e314a1b-1d43-46c2-9524-7882c1bdbd04"
                     * ,"caececad-0a0d-469c-a172-466b7426f3ab","177da8dd-6290-4495-abf1-68fc9a2704f2","80553cff-4a91-47e9-b074-db56b4743ef9","efe89f3a-7e08-43fe-8a15-129e01772f7d","1fff80d7-0451-40cc-a7d2-7c277fc93520",
                     * "1c8d6d37-5f77-4566-8b30-5d4bf02029e6","3550ac6e-3295-49d3-bd88-7fe0738cc9f1","a9785a4f-ac03-4713-9834-309d2b515ab0","270dc238-f371-43d8-950f-aec4c7aef5c4"]}
                     */
                    String itemBankId = yiTiHuaSimpileAnswerInfo.getContent().getItemBankId();
                    List<String> idList = Lists.newArrayList();

                    for (YiTiHuaSimpileAnswerInfo.ContentDTO.ItemsDTO items : yiTiHuaSimpileAnswerInfo.getContent().getItems()) {
                        idList.add(items.getI1());
                    }

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("itemBankId", itemBankId);
                    jsonObject.put("idList", idList);
                    System.err.println("json:" + jsonObject.toJSONString());

                    String postUrl2 = "https://xjskk.open.com.cn/api/teacher/teacher-space-service/testQuestions/questionWithoutAnswer";
                    String questionDetails = HttpUtil.postJson(postUrl2, jsonObject, cookie, heads);
                    System.err.println("questionDetails:" + questionDetails);

                    QuestionDetail questionDetail = JSONObject.parseObject(questionDetails, QuestionDetail.class);


                    for (QuestionDetail.ContentDTO contentDTO : questionDetail.getContent()) {
                        Question question = new Question();
                        question.setTitle(contentDTO.getI2());
                        question.setScore(contentDTO.getI9() + 0.0);
                        int i3 = contentDTO.getI3();
                        question.setQuestionType(i3);
                        /**
                         *1-单选题
                         *2-多选题
                         *3-判断题
                         * 4-填空题
                         *
                         * 6-名词解释 |问答题|论述题
                         */


                        if (i3 <= 3) {
                            if (i3 == 1) {
                                question.setQuestionTypeDesc("单选题");
                            } else if (i3 == 2) {
                                question.setQuestionTypeDesc("多选题");
                            } else {
                                question.setQuestionTypeDesc("判断题");
                            }


                            List<Item> items = Lists.newArrayList();
                            question.setItems(items);
                            List<String> answers = contentDTO.getI6();
                            for (String answer : answers) {
                                Item item = new Item(answer, "");
                                items.add(item);
                            }

                            // 正确的答案所在的位置
                            List<String> correctIndex = contentDTO.getI7();
                            List<String> correctList = Lists.newArrayList();
                            for (String cIndex : correctIndex) {
                                int index = Integer.parseInt(cIndex);
                                correctList.add(answers.get(index));
                            }
                            String[] correctArray = new String[]{};
                            correctArray = correctList.toArray(correctArray);
                            System.err.println("correctArray:" + JSON.toJSONString(correctArray));
                            question.setCorrectArray(correctArray);

                            System.err.println("????????????111:" + JSON.toJSONString(question.getCorrectArray()));
                        } else {
                            if (i3 == 4) {
                                question.setQuestionTypeDesc("填空题");
                            } else {
                                question.setQuestionTypeDesc("简答题");
                            }
                            // 正确的答案所在的位置
                            List<String> answers = contentDTO.getI6();
                            String[] correctArray = new String[]{};
                            correctArray = answers.toArray(correctArray);
                            question.setCorrectArray(correctArray);
                        }

                        questions.add(question);

                        System.err.println("??????????????222:" + JSON.toJSONString(question.getCorrectArray()));
                    }


                    //  FileUtils.write(new File("D:\\新疆一体化\\"+courseName+"\\"+pageIndex+".json"), JSONObject.toJSONString(questionDetails, SerializerFeature.PrettyFormat),"utf-8");
                    FileUtils.write(new File("D:\\新疆一体化2\\" + courseName + "\\" + pageIndex + ".json"), questionDetails);

                    pageIndex++;
                    if (pageIndex > page) {
                        hashNextPage = false;
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                }
            }


            while (hashNextPage) {
                Thread.sleep(5000);
            }

            //   Collections.sort(questions);
            List<Map<String, Object>> answers = new ArrayList<>();
            for (Question question : questions) {
                String title = question.getTitle();
                title = Util.dealContent(title);
                Map<String, Object> answerMap = new HashMap<>();
                answerMap.put("questionType", question.getQuestionType());
                answerMap.put("answerType", "click");
                answerMap.put("questionTypeDesc", question.getQuestionTypeDesc());
                answerMap.put("questionTitle", title);
                //   answerMap.put("questionCode", MD5Utils.encode(subjectName + title));
                answerMap.put("questionCode", question.getQuestionCode());
                answerMap.put("items", question.getItems());
                answerMap.put("answers", question.getCorrectArray());
                System.err.println("question.getCorrectArray():" + JSON.toJSONString(question.getCorrectArray()));
                answerMap.put("score", question.getScore());
                answers.add(answerMap);
            }

            FileUtils.write(new File("D:\\新疆一体化2\\" + courseName + "\\all.json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");


            Thread.sleep(5000);
        }
    }


//        driver.quit();


    }


